"""
Verify Review API - Test HiAgent create_conversation

Test correct way to call HiAgent API for review service
"""
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from dotenv import load_dotenv
load_dotenv()

import sys
from pathlib import Path

# Add hiagent-chat module to path
hiagent_path = Path(__file__).parent.parent / "src" / "llm" / "hiagent-chat"
sys.path.insert(0, str(hiagent_path))

from config import HiAgentConfig, load_config
from client import HiAgentClient


def test_create_conversation():
    """Test creating a conversation using HiAgentClient"""

    print("=" * 70)
    print("Test Review API - Create Conversation")
    print("=" * 70)

    # Load config from environment
    print("\n1. Loading configuration...")
    config = load_config()

    print(f"   Base URL: {config.base_url}")
    print(f"   App Key: {config.app_key[:10]}...")

    # Create client
    print("\n2. Creating HiAgent client...")
    client = HiAgentClient(config)

    # Test create conversation
    print("\n3. Creating test conversation...")
    try:
        user_id = "test_review_user"
        inputs = {
            "system": "You are a helpful teacher who reviews student work."
        }

        conversation = client.create_conversation(user_id=user_id, inputs=inputs)

        print(f"\n[SUCCESS] Conversation created!")
        print(f"   Conversation ID: {conversation.app_conversation_id}")
        print(f"   Conversation Name: {conversation.conversation_name}")
        print(f"   Created At: {conversation.create_time}")

        return True, conversation.app_conversation_id

    except Exception as e:
        print(f"\n[FAILED] Error creating conversation: {e}")
        import traceback
        traceback.print_exc()
        return False, None


def test_chat_in_conversation(conversation_id: str):
    """Test sending a message in the conversation"""

    print("\n" + "=" * 70)
    print("Test Chat in Conversation")
    print("=" * 70)

    config = load_config()
    client = HiAgentClient(config)

    try:
        print(f"\n1. Sending test message to conversation {conversation_id}...")

        query = """Please review the following answer:

Question: What is photosynthesis?

Student Answer: Photosynthesis is when plants make food from sunlight.

Please provide feedback."""

        response = client.chat(
            conversation_id=conversation_id,
            query=query,
            user_id="test_review_user"
        )

        print(f"\n[SUCCESS] Received response!")
        print(f"   Message ID: {response.message_id}")
        print(f"\n   AI Response:")
        print(f"   {response.content}")

        return True

    except Exception as e:
        print(f"\n[FAILED] Error in chat: {e}")
        import traceback
        traceback.print_exc()
        return False


if __name__ == "__main__":
    # Test 1: Create conversation
    success, conv_id = test_create_conversation()

    if not success:
        print("\n[FAILED] Could not create conversation. Please check your configuration.")
        sys.exit(1)

    # Test 2: Chat in conversation
    success = test_chat_in_conversation(conv_id)

    if success:
        print("\n" + "=" * 70)
        print("[SUCCESS] All tests passed!")
        print("=" * 70)
        sys.exit(0)
    else:
        print("\n" + "=" * 70)
        print("[FAILED] Some tests failed.")
        print("=" * 70)
        sys.exit(1)
